package com.hison.tandainbao.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hison.tandainbao.entiy.pojo.domain.TbBlog;
import com.hison.tandainbao.entiy.pojo.domain.TbFollow;
import com.hison.tandainbao.entiy.pojo.domain.User;
import com.hison.tandainbao.entiy.pojo.dto.ScrollResult;
import com.hison.tandainbao.entiy.pojo.dto.UserDTO;
import com.hison.tandainbao.mapper.TbBlogMapper;
import com.hison.tandainbao.response.ResponseResult;
import com.hison.tandainbao.service.TbBlogService;
import com.hison.tandainbao.service.TbFollowService;
import com.hison.tandainbao.service.UserService;
import com.hison.tandainbao.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author hison
 * @description 针对表【tb_blog】的数据库操作Service实现
 * @createDate 2024-03-21 20:47:41
 */
@Service
public class TbBlogServiceImpl extends ServiceImpl<TbBlogMapper, TbBlog>
        implements TbBlogService {

    @Autowired
    private TbBlogMapper mapper;

    @Autowired
    private UserService userService;

    @Autowired
    private TbFollowService tbFollowService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult publishBlog(TbBlog blog) {
        UserDTO user = UserHolder.getUser();
        Long id = user.getId();
        blog.setUserId(id);
        blog.setStatus(0);
        int i = mapper.insert(blog);
        if (i < 1) {
            return ResponseResult.error("添加失败");
        }
        //3.查询笔记作者（当前登录用户）的所有粉丝   select *  from  tb_follow where follow_user_id = ?
        List<TbFollow> follows = tbFollowService.query().eq("follow_user_id", user.getId()).list();
        //4.推送笔记id给所有粉丝
        for (TbFollow follow : follows) {
            //4.1 获取粉丝id
            Long userId = follow.getUserId();
            //4.2 推送
            String key = "feed:" + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return ResponseResult.ok("添加成功,待管理员审核");
    }

    @Override
    public ResponseResult getAllBlog(Integer current) {
        // 根据用户查询
        Page<TbBlog> page = query()
                //根据点赞数降序排列
                .orderByDesc("liked")
                .eq("status", 1)
                //分页
                .page(new Page<>(current, 10));
        //查询出当前页的博客信息
        List<TbBlog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            //查询该博客的用户信息 （头像  昵称等）
            queryBlogUser(blog);
            //查看有没有被点赞 （查看当前用户是否有为该用户点赞）
            isBlogLiked(blog);
        });

        return ResponseResult.ok(records);
    }

    @Override
    public ResponseResult likeBlog(Long id) {
        //1. 获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断当前登录用户是否已经点赞
        String key = "blog:liked:" + id;
        //判断zset中是否存在当前用户，没有则返回空   分数存在说明已经点赞了
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score == null) {
            //3.如果未点赞，可以点赞
            //3.1数据库点赞数 +1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            //3.2保存用户到redis集合   Zadd  key  value   score
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4.如果已点赞  取消点赞
            //4.1 数据库点赞数 -1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            //4.2 把用户从redis的set集合中移除
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult queryMyBlog(Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<TbBlog> page = query()
                .eq("user_id", user.getId()).page(new Page<>(current, 10));
        // 获取当前页数据
        List<TbBlog> records = page.getRecords();
        return ResponseResult.ok(records);
    }

    @Override
    public ResponseResult queryBlogById(Long id) {
        //1.查询blog
        TbBlog blog = baseMapper.selectById(id);
        if (blog == null) {
            return ResponseResult.error("笔记不存在");
        }
        //查询相关用户信息  获取该博客的详细信息
        queryBlogUser(blog);
        //查询blog是否被当前登录用户点赞了
        isBlogLiked(blog);
        return ResponseResult.ok(blog);
    }

    @Override
    public ResponseResult querBlogLikes(Long id) {
        String key = "blog:liked:" + id;
        //查询top5的点赞用户  rang   key   0  4        查询前五个点赞的属性
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return ResponseResult.ok(Collections.emptyList());
        }
        //解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //根据用户id查询用户   where id  in (5,1) order by FIELD (id,5,1);
        // 将集合转为字符串
        String join = StrUtil.join(",", ids);
        // List<User> users = userService.listByIds(ids);
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids)
                .last("order by FIELD(id," + join + ")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //返回
        return ResponseResult.ok(userDTOS);
    }

    @Override
    public ResponseResult queryBlogFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱   ZREVRANGFBYSCORE  key   Max  min    limit   offset   cunt    表示查询 min -> max  范围之间的数据  起始偏移量为offset  总数据为count
        String key = "feed:" + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(
                key, 0, max, offset, 3
        );
        if (typedTuples.isEmpty() || typedTuples == null) {
            return ResponseResult.ok();
        }
        //3.解析数据：blogID     minTime时间戳   offset
        List<Long> ids = new ArrayList<>(typedTuples.size()); //指定大小
        long minTime = 0;
        int os = 1; //计数器
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //获取id
            String idStr = tuple.getValue();
            ids.add(Long.valueOf(idStr));
            //获取分数 (时间戳)
            long time = tuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time; //保证了装的是最后一个时间  获取最小时间
                os = 1;   //计数
            }
        }
        //4.根据id查询blog
        String idStr = StrUtil.join(",", ids);
        //List<Blog> blogs = listByIds(ids);// 使用in语句查询
        List<TbBlog> blogs = query()
                .in("id", ids)
                .last("order by FIELD(id," + idStr + ")")
                .list();
        for (TbBlog blog : blogs) {
            //查询相关用户信息
            queryBlogUser(blog);
            //查询blog是否被点赞了
            isBlogLiked(blog);
        }
        //5.封装返回
        ScrollResult result = new ScrollResult();
        result.setList(blogs);
        result.setOffset(os);
        result.setMinTime(minTime);
        return ResponseResult.ok(result);
    }

    @Override
    public ResponseResult deleteBlog(String id) {
        QueryWrapper<TbBlog> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        boolean remove = remove(wrapper);
        if (!remove) {
            return ResponseResult.error("删除失败");
        }

        return ResponseResult.ok("删除成功");
    }

    @Override
    public ResponseResult updateStatusByAdmin(String blogId, Integer status) {
       mapper.updateStatusByAdmin(blogId, status);
        return ResponseResult.ok("审核成功");
    }

    @Override
    public ResponseResult getBlogByName(String name) {
        List<TbBlog> list = mapper.getBlogByName(name);
        // 查询用户
        list.forEach(blog -> {
            //查询该博客的用户信息 （头像  昵称等）
            queryBlogUser(blog);
            //查看有没有被点赞 （查看当前用户是否有为该用户点赞）
            isBlogLiked(blog);
        });
        return ResponseResult.ok(list);
    }

    @Override
    public ResponseResult getMyLike() {
        Long id = UserHolder.getUser().getId();
        List<TbBlog> list = query().eq("status", 1).eq("user_id", id).orderByDesc("liked").list();
        list.forEach(blog -> {
            //查询该博客的用户信息 （头像  昵称等）
            queryBlogUser(blog);
            //查看有没有被点赞 （查看当前用户是否有为该用户点赞）
            isBlogLiked(blog);
        });
        return ResponseResult.ok(list);
    }

    @Override
    public ResponseResult getAllBlogByAdmin(Integer current, Integer total) {
        // 根据用户查询
        Page<TbBlog> page = query()
                //根据点赞数降序排列
                .orderByAsc("status","create_time")
                //分页
                .page(new Page<>(current, total));
        //查询出当前页的博客信息
        List<TbBlog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            //查询该博客的用户信息 （头像  昵称等）
            queryBlogUser(blog);
        });

        return ResponseResult.ok(records);
    }

    /**
     * 判断是否点赞
     *
     * @param blog 博客
     * @return
     * @author $USER$
     * @date 2024/03/31
     * @see TbBlog
     * @since version
     */
    private void isBlogLiked(TbBlog blog) {
        //1. 获取登录用户
        //  Long userId = UserHolder.getUser().getId();//会报空指针异常
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //用户未登录无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        //2.判断当前登录用户是否已经点赞
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }


    /**
     * 查询博客用户
     *
     * @param blog 博客
     * @return
     * @author $USER$
     * @date 2024/03/31
     * @see TbBlog
     * @since version
     */
    private void queryBlogUser(TbBlog blog) {
        //2.查询用户相关信息
        //根据用户id
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setUserIcon(user.getUserIcon());
    }


}
